package io.jee.runshan.controller;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

@Controller
@RequestMapping("/api/upload")
public class UploadController {

	/**
	 * 文件上传
	 * @param request
	 * @param response
	 * @param folder  /目录名称/
	 * @param fileName 文件名称
	 * @throws Exception
	 */
	@RequestMapping(value = "/file" ,produces = {"application/json"})
	@ResponseBody
	public Map<String, Object> file(HttpServletRequest request, HttpServletResponse response,
			String folder, String fileName,Integer seq) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
			MultipartFile multipartFile = multipartRequest.getFile("file");
			fileName = UUID.randomUUID().toString();
			//获取文件的后缀
			String suffix = multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().lastIndexOf("."));
			//创建目录
			String rootPath = "/upload";
			SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd");
			String path = rootPath + folder + dateformat.format(new Date());//如：/productImg/2015-01-21
			String realPath = request.getSession().getServletContext().getRealPath(path); 
			File file = new File(realPath);
	        if(!file.exists()){
	        	file.mkdirs();
	        }
	        multipartFile.transferTo(new File(realPath + "/" + fileName + suffix));
	        String filePath = path + "/" + fileName + suffix;
	        map.put("filePath", filePath);
	        map.put("seq", seq);
	        map.put("msg", "文件上传成功");
			map.put("success", true);
		} catch (Exception e) {
            e.printStackTrace();
            map.put("msg", "未知错误:" + e.getMessage());
            map.put("success", false);
        }
		return map;
	}
}
